var globalCount = 0;
var menuIds;
var menuIdsa;
$("#fakeloader").fakeLoader({
	timeToHide : 10000, //Time in milliseconds for fakeLoader disappear
	zIndex : 999, // Default zIndex
	spinner : "spinner6", //Options: 'spinner1', 'spinner2', 'spinner3', 'spinner4', 'spinner5', 'spinner6', 'spinner7' 
	bgColor : "#fff", //Hex, RGB or RGBA colors
});
setTimeout(function() {
	$('body').css('opacity', '1');
	$('body').attr("class", "gray-bg") //添加样式
}, 100);

$(document).ready(function() {
	selectRole();
});

var returnAllCount = function() {
	if (globalCount == 1) {
		setTimeout(function() {
			$('#fakeloader').css('display', 'none');
		}, 500);
	}
}
//初始化表格数据
var selectRole = function() {
	$('#allBlog').bootstrapTable({
		method : 'post',
		url : "../selectAllRoles",
		dataType : "json",
		striped : false, //使表格带有条纹  
		pagination : true, //在表格底部显示分页工具栏  
		pageSize : 10,
		pageNumber : 1,
		sortStable : true,
		sortable : true,
		pageList : [ 10, 20, 50, 100 ],
		idField : "id", //标识哪个字段为id主键  
		showToggle : false, //名片格式  
		cardView : false, //设置为True时显示名片（card）布局  
		showColumns : true, //显示隐藏列    
		showRefresh : true, //显示刷新按钮  
		//singleSelect: true,//复选框只能选择一条记录  
		search : true, //是否显示搜索框
		searchOnEnterKey : true, //设置为 true时，按回车触发搜索方法，否则自动触发搜索方法
		//clickToSelect: true,//点击行即可选中单选/复选框  
		queryParams : queryParams, //参数  
		showFullscreen:true,  //全屏按钮
		//queryParamsType: "limit", //查询参数组织方式
		sidePagination : "server", //服务端处理分页
		silent : true, //刷新事件必须设置  
		searchTimeOut : 500, //设置搜索超时时间
		toolbarAlign : 'left', //工具栏对齐方式
		buttonsAlign : 'right', //按钮对齐方式
		toolbar : '#toolbar', //指定工作栏
		searchAlign : 'right',
		// singleSelect : true,
		contentType : "application/x-www-form-urlencoded",
		formatLoadingMessage : function() {
			
			return "请稍后，正在加载中...";
		},
		formatNoMatches : function(res) { //没有匹配的结果  
			return "无符合条件的记录/您没有查看权限";
		},
		responseHandler : function(res) {
			console.log(res);
			if(res=="201"){
				swal({title:"未授权",width:"100",height:"50px", text:"",showConfirmButton:false, type:"warning",timer:"1000"}); 
				return {
					"total" : 0, //总页数
					"rows" : null //数据
				};
			}
			return {
				"total" : res.pageInfo.total, //总页数
				"rows" : res.pageInfo.list //数据
			};
		},
		columns : [
			{
				checkbox : true,
				width : '3%',
				align : 'center',
				valign : 'middle',
			},
			{
				title : '序号',
				align : 'center',
				valign : 'middle',
				width : '4%',
				formatter : function(value, row, index) {
					var index1 = index + 1;
					var id = '<span title="ID:' + row.id + '">' + index1 + '</span>';
					return id;
				}
			},
			{
				title : '角色名',
				field : 'roleName',
				align : 'center',
				valign : 'middle',
				width : '8%',
				cellStyle : formatTableUnit,
				formatter : operateOpinionFormatter
			},
			{
				title : '角色签名',
				field : 'roleSign',
				align : 'center',
				width : '8%',
				cellStyle : formatTableUnit,
				formatter : operateOpinionFormatter
			},
			{
				title : '创建人',
				field : 'roleName',
				align : 'center',
				width : '13%',
				cellStyle : formatTableUnit,
				formatter : operateOpinionFormatter
			},

			{
				title : '备注',
				field : 'remark',
				align : 'center',
				width : '10%',
				cellStyle : formatTableUnit,
				formatter : operateOpinionFormatter
			},
			{
				title : '创建日期',
				field : 'gmtCreate',
				align : 'center',
				width : '15%',
				formatter : function(value, row, index) {
					return Format(row.gmtCreate, "yyyy-MM-dd hh:mm:ss");
				}
			},
			{
				title : '操作',
				field : 'id',
				align : 'center',
				width : '15%',
				formatter : function(value, row, index) {
					//修改用户	
					var a = '<a  class=" btn-sm btn-info" href="#" data-toggle="modal" data-target="#myModal" onclick="selectRoleById(\'' + row.id + '\')"><i class="fa fa-edit" ></i> 修改</a></a> ';
					//删除用户
					var c = '<a  class=" btn-sm btn-danger"  onclick="operation(' + row.id + ',\'删除\')"><i class="fa fa-remove" ></i> 删除</a> ';
					//冻结账户
					if(row.id==1){
						return a
					}else{
						return a+c;
					}
				}
			}
		]
	});
	globalCount++;
	returnAllCount();
}

//传参数到后台
function queryParams(params) {
	return {
		pageSize : params.limit,
		page : (params.offset) / params.limit + 1,
		roleName : $(".form-control").val(),
		roleSign : $(".form-control").val(),
		status : 1
	}
}

//设置 字数不超过宽度限制
var operateOpinionFormatter = function(value, row, index) {
	var title = "";
	var content = $(".form-control").val();
	var contentLow = $(".form-control").val().toLowerCase();
	var strStartIndex = '';
	var strEndIndex = '';
	if (value.search(content) != -1 || value.toLowerCase().search(contentLow) != -1) {
		var strs = new Array();
		strs = value.split("");
		strStartIndex = value.indexOf(content);
		strEndIndex = strStartIndex + content.length - 1;
		if (value.toLowerCase().search(contentLow) != -1) {
			strStartIndex = value.toLowerCase().indexOf(contentLow);
			strEndIndex = strStartIndex + contentLow.length - 1;
		}
		for (var i = 0; i < strs.length; i++) {
			if (i >= strStartIndex && i <= strEndIndex) {
				title += '<span style="color:#000;font-weight:bold;">' + strs[i] + '</span>';
			} else {
				title += '<span >' + strs[i] + '</span>';
			}
		}
	} else {
		title = value;
	}
	if (value.length > 15) {
		var num = strEndIndex - strStartIndex;
		var index = strStartIndex - 4;
		if (index < 0) {
			index = 0;
		}
		if (content == "") {
			return "<span title='" + value + "'>" + title.substring(0, 150) + "..." + "</span>";
		} else {
			return "<span title='" + value + "'>" + title.substring(15 * index, (15 * index) + (num + 1) * 51 + (9 - num) * 15) + "..." + "</span>";
		}
	} else {
		return "<span  title='" + value + "'>" + title.substring(0, title.length) + "</span>";
	}
}

var formatTableUnit = function(value, row, index) {
	return {
		css : {
			"overflow" : 'hidden',
			"text-overflow" : 'ellipsis',
			"white-space" : 'nowrap'
		}
	};
};


//获取行号  
var getSelectRows = function(status) {
	var date = $("#allBlog").bootstrapTable('getSelections');
	var idArray = new Array();
	var title = '';
	var text = '';
	if(date.length<1){
		swal("请选择需要操作的用户", "", "warning","22em");
		return false;
	}
	if (status == 1) {
		title = '确定要删除这' + date.length + '个用户吗';
		text = '删除后将不显示在在列表，可以在回收站还原！';
	} else if (status == 2) {
		title = '确定要将这' + date.length + '个用户冻结吗';
		text = '冻结后,用户将无法登录';
	} 
	swal({
		title : title,
		text : text,
		type : "warning",
		showCancelButton : true,
		confirmButtonColor : "#DD6B55",
		confirmButtonText : "确定",
		closeOnConfirm : false
	}, function() {
		console.log(date);
		if (status == 1) {
				for (var i = 0; i < date.length; i++) {
					if(date[i].roleSign=="superAdmin"){
						swal({title:"superAdmin角色不允许删除",width:"100",height:"50px", text:"",showConfirmButton:false, type:"warning",timer:"1000"}); 
						break;
					}
					idArray[i] = date[i].id;
					operationRole(idArray[i], -1, null, null); //参数2表示  放入回收站
				}
			
		} else if (status == 2) {
			for (var i = 0; i < date.length; i++) {
				if(date[i].bloger.username=="admin"){
					swal({title:"admin用户不允许冻结",width:"100",height:"50px", text:"",showConfirmButton:false, type:"warning",timer:"1000"}); 
					break;
				}
				idArray[i] = date[i].bloger.id;
				operationRole(idArray[i], 2, null, 1); // 冻结
			}
		}
		})
};

var operation = function(id, op) {
	var title = "";
	var text = "";
	if (op == "还原") {
		title = '确定要移出回收站吗';
		text = '移出后,将显示在正常用户列表';
	} else if (op == "删除") {
		title = '确定要删除吗';
		text = '删除后,将显示在正常用户列表';
	} else if (op == "冻结") {
		title = '确定要冻结吗';
		text = '冻结后,账户将无法登陆';
	} else if (op == "解冻") {
		title = '确定要解冻账户吗';
		text = '解冻账户后,可以正常登陆';
	}
	swal({
		title : title,
		text : text,
		type : "warning",
		showCancelButton : true,
		confirmButtonColor : "#DD6B55",
		confirmButtonText : "确定",
		closeOnConfirm : false
	}, function() {
		if (op == "删除") {
			operationRole(id, -1, null, null)
		} else if (op == "冻结") {
			operationRole(id, 2, null, null)
		} else if (op == "解冻") {
			operationRole(id, 1, null, null)
		} else if (op == "还原") {
			operationRole(id, 1, null, null)
		}
	});
};

//博客的操作
var operationRole = function(idArray, status, sex, roleId) {
	var param = '';
	if (status != null) {
		if (status == (-1)) {
			prarm = '将ID为<span class="text-info">' + idArray + '</span>的用户<span class="text-success">删除</span>'
		} else if (status == 0) {
			prarm = '将ID为<span class="text-info">' + idArray + '</span>的用户<span class="text-navy">冻结</span>'
		}
		param = {
			'id' : idArray,
			'status' : status,
			prarm : prarm,
		};
	}
	$.ajax({
		url : '../updateRole',
		type : 'post',
		data : param,
		dataType : 'json',
		success : function(data) {
			//查询成功
			if (data.status == 200) {
				$("#allBlog").bootstrapTable('refresh');
				swal("更新成功", "", "success");
			} else if(data=="201") {
				swal({title:"未授权",width:"100",height:"50px", text:"",showConfirmButton:false, type:"warning",timer:"1000"}); 
			}else{
				swal("更新失败", "请重新操作", "error");
			}
		},
		error : function() {
			swal("更新错误", "请重新操作", "error");
		}
	});
}


//格式化时间
function Format(datetime, fmt) {
	if (parseInt(datetime) == datetime) {
		if (datetime.length == 10) {
			datetime = parseInt(datetime) * 1000;
		} else if (datetime.length == 13) {
			datetime = parseInt(datetime);
		}
	}
	datetime = new Date(datetime);
	var o = {
		"M+" : datetime.getMonth() + 1, //月份   
		"d+" : datetime.getDate(), //日   
		"h+" : datetime.getHours(), //小时   
		"m+" : datetime.getMinutes(), //分   
		"s+" : datetime.getSeconds(), //秒   
		"q+" : Math.floor((datetime.getMonth() + 3) / 3), //季度   
		"S" : datetime.getMilliseconds() //毫秒   
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (datetime.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}
function updateRole(id) {
	getAllSelectNodes();
	$('#menuIds').val(menuIds);
	console.log($("#menuIds").val());
	var prarm = '修改角色';
	var params = {
		'id' : id,
		'roleName' : $("roleName").val(),
		'roleSign' : $("#roleSign").val(),
		'remark' : $("#remark").val(),
		'status' : 1,
		'menuIds' : $("#menuIds").val(),
		prarm : prarm
	};
	$.ajax({
		url : '../updateRole',
		type : 'post',
		data : params,
		dataType : 'json',
		success : function(data) {
			console.log(data);
			if (data.status == 200) {
				$("#myModal").modal('hide');
				var title = "更新成功";
				var text = "用户信息更新成功";
				$('#allBlog').bootstrapTable('refresh');
				swal({
					title : title,
					text : text,
					type : "success",
					timer : 1500,
				});
			} else if(data == "201"){
				swal({title:"未授权",width:"100",height:"50px", text:"",showConfirmButton:false, type:"warning",timer:"1000"}); 
			}else if(data == "500"){
				swal("服务器错误", "请重新操作", "error");
			}else{
				swal("未知错误", "请重新操作", "error");
			}
		},
		error : function() {
			swal("更新错误", "请重新操作", "error");
		}
	});

}
//添加用户
function addBloger() {
	getAllSelectNodesa();
	$('#menuIdsa').val(menuIdsa);
	var roleName=$("#aroleName").val();
	var roleSign=$("#aroleSign").val();
	var remark=$("#aremark").val();
	if(roleName==""||roleName==null){
		swal("角色名不能为空", "", "warning");
		return false;
	}
	if(roleSign==""||roleSign==null){
		swal("角色签名不能为空", "", "warning");
		return false;
	}
	var prarm="新增用户";
	var params = {
		'roleName' : roleName,
		'roleSign' : roleSign,
		'remark' : remark,
		'menuIds' : $("#menuIdsa").val(),
		'status':1,
		'prarm' : prarm
	};
	$.ajax({
		url : '../addRole',
		type : 'post',
		data : params,
		dataType : 'json',
		success : function(data) {
			if (data.status == 200) {
				$("#myModalAdd").modal('hide');
				clearAdd();
				var title = "添加成功";
				var text = "角色添加成功";
				$('#allBlog').bootstrapTable('refresh');
				swal({
					title : title,
					text : text,
					type : "success",
					timer : 1500,
				});
			} else if(data == "201"){
				swal({title:"未授权",width:"100",height:"50px", text:"",showConfirmButton:false, type:"warning",timer:"1000"}); 
			}else{
				swal("添加错误", "请重新操作", "error");
			}
		},
		error : function() {
			alert("异常");
			swal("添加错误", "请重新操作", "error");
		}
	});

}
function loadMenuTree(menuTree) {
	$('#mtree').html("<div id='menuTree'></div>");
	$('#menuTree').jstree({
		"plugins" : [ "wholerow", "checkbox" ],
		'core' : {
			'data' : menuTree
		},
		"checkbox" : {
			//"keep_selected_style" : false,
			//"undetermined" : true
			//"three_state" : false,
			//"cascade" : ' up'
		}
	});
	$('#menuTree').jstree('open_all');
}


function getAllSelectNodes() {
	var ref = $('#menuTree').jstree(true); // 获得整个树
	menuIds = ref.get_selected(); // 获得所有选中节点的，返回值为数组
	$("#menuTree").find(".jstree-undetermined").each(function(i, element) {
		menuIds.push($(element).closest('.jstree-node').attr("id"));
	});
	console.log(menuIds); 
}
function getMenuTreeData(id) {
	//var id = $('#id').val();
	$.ajax({
		type : "POST",
		url : "../tree/" + id,
		success : function(data) {
			console.log(data);
			loadMenuTree(data);
		}
	});
}
function getMenuTreeDataa() {
	$.ajax({
		type : "POST",
		url : "../tree",
		success : function(data) {
			console.log(data);
			loadMenuTreea(data);
		}
	});
}

function loadMenuTreea(menuTree) {
	$('#mtreea').html("<div id='menuTreea'></div>");
	$('#menuTreea').jstree({
		"plugins" : [ "wholerow", "checkbox" ],
		'core' : {
			'data' : menuTree
		},
		"checkbox" : {
		}
	});
	$('#menuTreea').jstree('open_all');
}

function getAllSelectNodesa() {
	var ref = $('#menuTreea').jstree(true); // 获得整个树
	menuIdsa = ref.get_selected(); // 获得所有选中节点的，返回值为数组
	$("#menuTreea").find(".jstree-undetermined").each(function(i, element) {
		menuIdsa.push($(element).closest('.jstree-node').attr("id"));
	});
	console.log(menuIdsa); 
}


function clearAdd(type){
	$("#aroleName").val("");
	$("#aroleSign").val("");
	$("#aremark").val("");
	getMenuTreeDataa();
}
//查看角色信息
function selectRoleById(id) {
	var param = {
		id : id
	}
	$.ajax({
		url : '../selectRoleById',
		type : 'post',
		data : param,
		dataType : 'json',
		success : function(data) {
			//查询成功
			if (data.status == 200) {
				console.log(data,"通过ID查找的角色");
				$(".newsview").find("#roleName").val(data.role.roleName);
				$(".newsview").find("#roleSign").val(data.role.roleSign);
				$(".newsview").find("#remark").val(data.role.remark);
				getMenuTreeData(id);
				var update = '<button  class="J_menuItem btn btn-white" onclick="updateRole(' + data.role.id + ')">保存</button>';
				$(".modal-footer").find(".update").html(update);
				
			}
			$('pre').each(function(i, block) {
				hljs.highlightBlock(block);
			});
		},
		error : function() {
			swal("查询错误", "请重新操作", "error");
		}
	});
}